package API.File.Practise;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static API.File.Practise.MainFile.mainFilePath;

public class _6GetFilesTypeNum {
    public static void main(String[] args) {
        getFilesTypeNum(new File(".\\")).forEach((String type, Integer num) -> {
            System.out.println(type + ":" + num);
        });
    }

    public static Map<String, Integer> getFilesTypeNum(File file) {
        Map<String, Integer> map = new HashMap<>();
        if (file.isFile()) {
            String type = getFileType(file.getName());
            if (type != null) {
                if (map.containsKey(type)) {
                    map.put(type, map.get(type) + 1);
                } else {
                    map.put(type, 1);
                }
            }
        } else if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.isFile()) {
                    String type = getFileType(f.getName());
                    if (type != null) {
                        if (map.containsKey(type)) {
                            map.put(type, map.get(type) + 1);
                        } else {
                            map.put(type, 1);
                        }
                    }
                } else if (f.isDirectory()) {
                    map = concat(map, getFilesTypeNum(f));
                }
            }
        }
        return map;
    }

    public static String getFileType(String fileName) {
        String[] params = fileName.split("\\.");
        if(params.length >= 2) {
            return params[params.length - 1];
        } else {
            return null;
        }
    }

    public static Map<String, Integer> concat(Map<String, Integer> a, Map<String, Integer> b) {
        Set<Map.Entry<String, Integer>> mapSet = b.entrySet();
        for (Map.Entry<String, Integer> entry : mapSet) {
            if (a.containsKey(entry.getKey())) {
                a.put(entry.getKey(), a.get(entry.getKey()) + entry.getValue());
            } else {
                a.put(entry.getKey(), entry.getValue());
            }
        }
        return a;
    }
}
